from dirstate.utils import statusSvn,getSvnUpFiles,getSvnLocalRev, debug,HSVG_TAG_PRE,updateSvnRepo
from otherparty.common import run_hg, run_svn, run_hgtk, run_command

def upLastSynch():
	tag = HSVG_TAG_PRE+str(getSvnLocalRev())
	print run_hg(['up','-v',tag])
	
def outstandingChanges():
	return u'' != run_hg(['st'])

def waitForOthersResolutions():
	raw_input('-> presione una tecla cuando termine de resolver conflictos manuales o de compilacion...')
	
def getLastHgRev():
	return int(run_hg(['log','-q','-l','1']).split(':')[0])

def commitHgToSvn():
	"""Sincroniza repositorio hg con svn"""
	localCh = statusSvn()
	repoCh = getSvnUpFiles()
	localRev = getLastHgRev()
	initialSvnLocalRev = getSvnLocalRev()
	if localCh or repoCh:
		cmt = 'solo subo cambios'
		debug('complejidad: localCh = %s, repoCh = %s' % (bool(localCh) ,bool(repoCh)))
		if raw_input()=='Y':
			try:
				if localCh and repoCh:				
					if outstandingChanges(): 
						print '-> commit de cambios locales'
						run_hgtk(['ci'])	# si es o no hgtk deberia ir por conf	
						localRev = getLastHgRev()
					print '-> update local a ultima synch'
					upLastSynch()
					print '-> update Svn total' # si hace un update o uno por revision en svn deberia estar por conf
					updateSvnRepo(doTag=False) # up svn + commit hg
					print '-> commit local de cambios svn'
					run_hg(['ci','-Am','commit SVN','--user','svn-users'])
					print '-> merge de branchs paralelos'
					run_hg(['merge'])
					waitForOthersResolutions()
					print '-> commit del merge'
					run_hg(['ci','-m','merge con rev '+str(getSvnLocalRev())])
					# si no hay mas cambios a bajar hago commit svn en otro caso hago otro update (sin tag)  + merge + compila ok hasta que no haya mas cambios a bajar
					while getSvnUpFiles():
						print '-> hay nuevos cambios en repositorio: update + resolucion + commit local'
						updateSvnRepo(doTag=False)
						waitForOthersResolutions()
						run_hg(['ci','-Am','commit SVN','--user','svn-rest'])
					cmt = 'synch con hsvg'
				if localCh:
					if not repoCh and outstandingChanges(): 
						print '-> commit de cambios locales'
						run_hgtk(['ci'])	# si es o no hgtk deberia ir por conf	
						localRev = getLastHgRev()
					print '-> commit en svn'
					commitSvn(comment=cmt,addremove=True)
				print '-> update desde svn'
				updateSvnRepo()
			except BaseException, err:
				debug(err)
				print 'Ocurrio un error, efectuando rollback...'
				print run_svn(['cleanup'])
				print run_svn(['up','--force','-r',initialSvnLocalRev])
				print run_hg(['strip','-f','-b',localRev + 1])
				print 'Rollback finalizado.'		
		else:
			print 'No se prosigue'
	else:
		print 'No hay cambios locales ni en el repo svn.'

def main():
	commitHgToSvn()

if __name__ == '__main__':
	main()